'use strict';

define(function(require,exports,module){
	
	var React = require('react');
	var $ = require('jquery');
	var moment = require('moment');

	var publicObj = require('lib/public');
	var token = publicObj.get_token();
	
	/*下拉框*/
	var SelectOption = require('components/partial/SelectOption');
	
	/*DATE下拉框*/
	var SelectOptionDate = require('components/partial/SelectOptionDate');
	
	//折线图
	var DayOpenLineDiagram = require('components/diagram/DayOpenLineDiagram');

	/**
	 * 启动次数多线图
	 * @type {[type]}
	 */
    var StartNumAreaMuliti = require('components/diagram/AreaDiagram/StartNumAreaMuliti');

    //TimeBucket
    var StartNumTimeBucket = require('./StartNumDiagram/TimeBucket');
	
    /*Loading状态*/
    var ReactLoading = require('../partial/ReactLoading');
	
	module.exports = React.createClass({
		handleDateChange:function(event){
			var date = event.target.value;
			this.setState({'date':date});
            this.setState({'hardware':''});
			this.loadData(date,'');
		},
		handleHardwareChange:function(event){
			var hardware = event.target.value;
			this.setState({'hardware':hardware});
			this.loadData(this.state.date,hardware);
		},
		loadData:function(date,hardware){
			
			this.setState({data:[]});
			if(date && hardware){
				var year = date.substring(0,4);
				var month = date.substring(4,6);
				var day = date.substring(6,8);
				var start_date = new XDate(year+"-"+month+"-"+day+" 00:00:00").toString('yyyy-MM-dd')+' 00:00:00';
				var end_date = new XDate(year+"-"+month+"-"+day+" 00:00:00").addDays(1).toString('yyyy-MM-dd')+' 00:00:00';

                var sql;
                if(hardware == 'iphone'){
                    sql = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),'%H') as time,\
                			count(*) as value\
						  FROM qeeniao.app_info\
						 where platform = 'iOS'\
						   and(create_time>= '"+start_date+"'\
						   and create_time< '"+end_date+"')\
						 group by time\
						 order by time ASC";

                }else if(hardware == 'android'){
                    sql = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),'%H') as time,\
                    		count(*) as value\
						  FROM qeeniao.app_info\
						 where platform = 'Android'\
						   and(create_time>= '"+start_date+"'\
						   and create_time< '"+end_date+"')\
						 group by time\
						 order by time ASC";
                }

				$.ajax({
					url:this.props.url,
					data:{sql:sql,'access_token':token},
					type:'post',
					dataType:'json',
					success:function(o){
						var tmp = [];
						tmp.push(o);
						if(o){
							if(this.isMounted()) {
								this.setState({'data': tmp});
							}
						}
					}.bind(this),
					error:function(xhr,status,err){
						console.error(sql,status,err.toString());
					}.bind(this)
				});
			}
		},
		getInitialState:function(){

			var date = new XDate().addDays(-10).toString("yyyyMMdd");
            

			var android_sql = "SELECT thedate AS name,\
						       count(*) AS value\
						  FROM qeeniao.app_info\
						 WHERE platform= 'Android'\
						   AND thedate>= "+date+"\
						 GROUP BY name\
						 ORDER BY name ASC";

			var ios_sql = "SELECT thedate AS name,\
						       count(*) AS value\
						  FROM qeeniao.app_info\
						 WHERE platform= 'iOS'\
						   AND thedate>= "+date+"\
						 GROUP BY name\
						 ORDER BY name ASC";

			return {
				'data':[],
				'date':'',
				'ajax_data':{'ios_sql':ios_sql,'android_sql':android_sql,'access_token':token}
			}
		},
		render:function(){
            var diagram;
            if(this.state.data.length > 0){
                diagram = this.state.data.map(function(item){
                    return (
                        <DayOpenLineDiagram className="" id="StartNum" id_name="StartNum" title="单日启动次数" yName="启动次数" yUnit="（时/次数）" url="" data={item} />
                    );
                });
            }else{
				diagram = <StartNumAreaMuliti className="" id="StartNumMuliti" id_name="StartNumMuliti" y="启动次数" title="每日启动次数" ajax_data={this.state.ajax_data} url={this.props.url} interval="300000"/>;
            }

			return (
				<div className="col-xs-6">
					<div className="row bgwhite">
						<div className="col-xs-4 bs-callout bs-callout-info">
							<h4>{this.props.title}: </h4>
						</div>
						<div className="col-xs-3 ">
							<SelectOptionDate handleDateChange={this.handleDateChange} data={this.props.data} />
						</div>
						<div className="col-xs-3">
							<SelectOption selectValue={this.state.hardware} handleChange={this.handleHardwareChange} data={this.props.hardware_data} formClass="hardwareForm" default_value="设备分类"/>
						</div>
						<div className="col-xs-2" style={{margin:'4px 0'}}>
							<button onClick={this.createHandle} className="btn btn-primary btn" data-toggle="modal" data-target="#StartNumTimeBucket">更多</button>
						</div>
                        <StartNumTimeBucket id="StartNumTimeBucket" url={this.props.url}/>
					</div>
					<div className="row">
					{diagram}
					</div>
				</div>
			);
		}
	});

});